package com.icef0x.tools;

import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;


/**
 * @author ywang
 */
public class DynamicCompile {
    
    private static DynamicCompile instance;
    private JavaCompiler jc;
    private ClassFileManager fm;
    
    public static synchronized DynamicCompile getInstance() {
        if (instance == null)
            instance = new DynamicCompile();
        return instance;
    }
    
    private DynamicCompile() { };

    public ClassLoader compile(JavaSourceFile[] files) {
        if (jc == null) {
            jc = ToolProvider.getSystemJavaCompiler();
            fm = new ClassFileManager(jc.getStandardFileManager(null, null, null));
        }
        
        Iterable<? extends JavaFileObject> iterable = Arrays.asList(files);
        CompilationTask task = jc.getTask(null, fm, null, null, null, iterable);
        boolean result = task.call();
        if (result) {
            System.out.println("compile complete");
        }
        return fm.getClassLoader(null);
    }
    
    public byte[] getClassBytecode(String name) throws ClassNotFoundException {
        if (fm == null) {
            throw new ClassNotFoundException();
        }

        byte[] bytes = fm.getClassBytecode(name);
        if (bytes == null)
            throw new ClassNotFoundException();
        return bytes;
    }
}
